<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/9/30
 * Time: 17:52
 */

namespace app\api\service;


use app\api\model\MessageFormid;
use app\api\model\User;
use app\api\model\WorkUser;
use app\lib\exception\OrderException;
use think\Cache;
use think\Config;
use think\Exception;

class DeliveryMessage extends WxMessage
{
//        const DELIVER_MSG_ID = "wpV50Eo7gw5wEwTMz5GU2qepHU0EW5IgVFe4Uvl9NU8";//订单通知
//        const USER_MSG_ID = "MI5LJ5ITDJJguhHnbsrrFWe8OhIiHNZv9fPIQgIhxkI";//消息通知
    /**
     * 发送微信支付模板小程序
     * @param $order
     * @param $data
     * @param string $tplJumpPage
     * @return bool
     * @throws Exception
     * @throws OrderException
     */
        public function sendDeliveryMessage($order,$data,$tplJumpPage=''){
            if (!$order){
                throw new OrderException();
            }
            $this->formID = $order->prepay_id;
            $this->page = $tplJumpPage;
            $this->prepareMessageDate($order,$data);
            $this->emphasisKeyWord = 'keyword2.DATA';
            $userInfo = $this->getUserOpenID($order->user_id);
            return parent::sendMessage($userInfo->openid);
        }
    /**
     * 传递服务消息
     * @param $message
     * @param string $tplJumpPage
     * @return bool
     * @throws OrderException
     */
        public function sendUserMessage($message,$t_id,$w_id,$tplJumpPage=''){
            if (!$message){
                throw new OrderException([
                    'msg'=>'信息不存在'
                ]);
            }
            $formid = $this->getFormId($t_id,$w_id,$message['to_client']);
            $this->formID = $formid;
            $this->page =$tplJumpPage;
            $this->offlineMessage($message);
            $user = $this->getUserOpenID($message['to_client']);
            return parent::sendMessage($user->openid);
        }

    /**
     * 订单消息准备
     * @param $order
     */
        private function prepareMessageDate($order,$info){
            $dt = new \DateTime();
            $data=[
                'keyword1'=>[
                    'value'=>$info['delivery_name']
                ],
                'keyword2'=>[
                    'value'=>$order->snap_name,
                    'color'=>'#27408B'
                ],
                'keyword3'=>[
                    'value'=>$order->order_no
                ],
                 'keyword4'=>[
                'value'=>$dt->format('Y-m-d H:i')
                ]
            ];
            $this->data = $data;
        }
    /**
     * 离线消息发送准备
     * @param $message
     */
    private function offlineMessage($message){
        $dt = new \DateTime();
        $data=[
            'keyword1'=>[
                'value'=>$message['user_name']
            ],
            'keyword2'=>[
                'value'=>$dt->format('Y-m-d H:i')
            ],
             'keyword3'=>[
            'value'=>'你有一条未读消息！'
            ],
        ];
        $this->data = $data;
    }
    /**
     * 获取用户信息
     * @param $uid
     * @return array|false|\PDOStatement|string|\think\Model
     */
        private function getUserOpenID($uid){
           return  User::getUserInfoByUid($uid);
        }

    /**
     * 没有formid
     * @param $wu_id
     * @param $uid
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws Exception
     */
        private function getFormId($t_id,$wu_id,$uid){
            //查询fromID
            //查询可以使用的formid
           try{
                $cache = Cache::connect(Config::get('cache.redis'));
                $cache->handler()->setOption(\Redis::OPT_SCAN,\Redis::SCAN_RETRY);
                $fromid = '';
                $key='';
                $iterator = null;
                while ($keys =  $cache->handler()->scan($iterator, 'message:t_id:'.$t_id.':wid:'.$wu_id.':uid:'.$uid.':formid:*')) {
                   $key = $keys[0];
                    $fromid = $cache->handler()->get($key);
                    //删掉使用的fromID
                }
               $cache->handler()->del($key);
                return $fromid;
            }catch (\Exception $exception){
                //失败
            }
        }
    /**
     * 获取销售信息
     * @param $wu_id
     * @return null|static
     */
        private function getWuOpenId($wu_id){
            return WorkUser::get($wu_id);
        }


}